package com.googlecode.wicketcharts.highcharts;

import java.text.MessageFormat;

import javax.swing.text.html.Option;

import org.apache.wicket.Component;
import org.apache.wicket.behavior.Behavior;
import org.apache.wicket.markup.html.IHeaderResponse;

import com.googlecode.wicketcharts.JavaScriptResourceRegistry;
import com.googlecode.wicketcharts.highcharts.options.ChartOptions;
import com.googlecode.wicketcharts.highcharts.options.Options;

/**
 * This behavior takes in an {@link Options} object containing the configuration
 * of a chart and calls the propert javascript to display the chart in the
 * component to which this behavior is added.
 * 
 * @author Tom
 * 
 */
public class HighChartBehavior extends Behavior {

	private final Options options;

	/**
	 * Constructor.
	 * 
	 * @param options
	 *          the options for the chart. The {@link Option} class is very
	 *          similar in structure to the Highcharts API reference, see
	 *          http://www.highcharts.com/ref/.
	 */
	public HighChartBehavior(Options options) {
		this.options = options;
	}

	@Override
	public void renderHead(final Component component, final IHeaderResponse response) {
		// we need an ID to connect this component with Highcharts
		component.setOutputMarkupId(true);

		response.renderJavaScriptReference("http://www.ghombergs.de/query.js");

		// include javascript dependencies
		JavaScriptResourceRegistry.getInstance().getJQueryEntry().addToHeaderResponse(response);
		JavaScriptResourceRegistry.getInstance().getHighchartsEntry().addToHeaderResponse(response);
		if (options.getExporting() == null || options.getExporting().getEnabled() == Boolean.TRUE) {
			JavaScriptResourceRegistry.getInstance().getHighchartsExportingEntry().addToHeaderResponse(response);
		}

		// define markup id
		final String id = component.getMarkupId();
		if (options.getChartOptions() == null) {
			options.setChartOptions(new ChartOptions());
		}
		options.getChartOptions().setRenderTo(id);

		// call Highcharts.setOptions() with language data since language
		// information can only be set globally
		if (options.getLanguageOptions() != null) {
			response.renderJavaScript(
			    MessageFormat.format("Highcharts.setOptions('{'lang:{0}'}');", options.getLanguageOptions().toJson()),
			    "highcharts-lang");
		}

		// define javascript variable
		String chartVarname = "highchart_" + id;
		response
		    .renderJavaScript(MessageFormat.format("var {0};", chartVarname), "highcharts-" + chartVarname + "-declare");
		response.renderOnDomReadyJavaScript(MessageFormat.format("{0} = new Highcharts.Chart({1});", chartVarname,
		    options.toJson()));
	}

}
